var navdata = require("../../database/data.js");
var amapFile = require("../../database/libs/bmap-wx.min.js");
var app = getApp()
//获取应用实例
Page({
  data: {
    share_isShow: false,
    canvasClose: true,
    hiddenNames: true,
    showCenterDialog: true,
    defName: false,
    more: true,
    isShow: '',
    showLogin: true,
    screen_isShow: true,
    screen_fload_show: false,
    contShow: true,
    screen: {},
    defult: 10,
    isPage: 1,
    requestLoading: true,
    requestLoadingComplete: true, //“没有数据”的变量，默认false，隐藏  
  },

  //上滑
  // onPageScroll: function(e) {
  //   //动态计算出分类区的高度
  //   let that = this;
  //   var query = wx.createSelectorQuery();
  //   query.select('#index_navs').boundingClientRect();
  //   query.exec(function(res) {
  //     var resHeight = res[0].height - 40;
  //     if(resHeight < e.scrollTop){
  //         that.setData({
  //           screen_fload_show: true,
  //         })
  //     } else{
  //       that.setData({
  //         screen_fload_show: false,
  //       })
  //     }
  //   })

  // },
  //分类详情
  onNavTo: function(event) {
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    var nav = event.currentTarget.dataset;
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].id == nav.id) {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
          changeColor: true,
        }

      } else {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      }
    }
    this.setData({
      screen: nav,
      hiddenNames: true,
      defName: false,
      more: true,
      isPage: 1,
      contShow: false,
    })
    var data = {
      cid: nav.id,
      num: "10",
      page: '1',
      isChoice: 0
    };
    var caseData = {
      city: this.data.city,
      cid: nav.id,
      num: '3',
    };
    var getApiContUrl = app.globalData.smsbaoApi + "/batch/sapi/get_sms_content";
    this.getApiData(getApiContUrl, data, "contents");
    var getApinavUrl = app.globalData.smsbaoApi + "/batch/sapi/get_case_content";
    this.getApiData(getApinavUrl, caseData, "caseData");
  },
  //上拉加载
  onReachBottom: function(event) {
    if (this.data.screen.name) {
      var getApiContUrl = app.globalData.smsbaoApi + "/batch/sapi/get_sms_content";
      var isPage = this.data.isPage++;
      var parameter = {
        cid: this.data.screen.id,
        num: this.data.defult,
        page: isPage,
        isChoice: 0
      };
      this.getApiData(getApiContUrl, parameter, "contents", "moreData")
      wx.showNavigationBarLoading();
    } else {
      this.setData({
        requestLoadingComplete: false,
      })
    }

  },

  //电话热线
  onMakePhone: function(e) {
    wx.makePhoneCall({
      phoneNumber: '400-716-3021',
    })
  },
  contact: function(e) {
    wx.navigateTo({
      url: "/pages/batch/contact_kefu/contact_kefu",
    })
  },
  //更多
  onNavMore: function(event) {
    this.setData({
      hiddenNames: !this.data.hiddenNames,
      defName: !this.data.defName,
      more: !this.data.more
    })
  },
  //筛选
  onScreenBtn: function(e) {
    if (this.data.screen != undefined && this.data.screen != '') {
      for (var i = 0; i < this.data.nav.length; i++) {
        if (this.data.nav[i].id == this.data.screen.id) {
          this.data.nav[i] = {
            id: this.data.nav[i].id,
            name: this.data.nav[i].name,
            tool_image: this.data.nav[i].tool_image,
            changeColor: true,
          }
        }
      }

    }
    this.setData({
      screen_isShow: !this.data.screen_isShow,
      nav: this.data.nav
    })
  },
  //关闭筛选
  onCloseScreen: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      this.data.nav[i] = {
        id: this.data.nav[i].id,
        name: this.data.nav[i].name,
        tool_image: this.data.nav[i].tool_image,
        changeColor: false,
      }
    }
    if (wx.pageScrollTo) { //判断这个方法是否可用
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    this.setData({
      requestLoading: true,
      requestLoadingComplete: true,
      nav: this.data.nav,
      screen_isShow: true,
      contShow: true,
      screen: {},
      isPage: 1,
    })
  },
  //获取定位
  onPosition: function(e) {
    let that = this;
    that.setData({
      positionShow: true
    })

    if (that.data.city == undefined || that.data.city == '') {
      wx.openSetting({
        success: function(res) {
          if (res.authSetting != '') {
            wx.getLocation({
              success: function(res) {
                var latitude = res.latitude //维度
                var longitude = res.longitude //经度        
                that.loadCity(latitude, longitude);
              },
            })
          }
        }
      })
    } else {
      wx.getLocation({
        success: function(res) {
          var latitude = res.latitude //维度
          var longitude = res.longitude //经度        
          that.loadCity(latitude, longitude);
        },
      })
    }

  },
  //筛选选择
  onScreenCate: function(e) {
    var cid = e.target.id;
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].id == cid) {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
          changeColor: true,
        }

      } else {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      }
    }
    this.setData({
      nav: this.data.nav
    })
  },
  //重置筛选
  onCateReset: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].changeColor == true) {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      } else {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      }
    }
    this.setData({
      nav: this.data.nav,
      contShow: true,
      screen: {},

    })
  },
  //提交筛选
  onCateSubmit: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].changeColor == true) {
        var screen = this.data.nav[i];
        if (wx.pageScrollTo) { //判断这个方法是否可用
          wx.pageScrollTo({
            scrollTop: 0
          })
        }
      }
    }
    var data = {
      cid: screen.id,
      num: "10",
      page: '1',
      isChoice: 0
    };

    this.setData({
      screen: screen,
      screen_isShow: !this.data.screen_isShow,
      alert_mask_isShow: false,
      hiddenNames: true,
      defName: false,
      more: true,
      isPage: 1,
      contShow: false,
    })
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    var getApiContUrl = app.globalData.smsbaoApi + "/batch/sapi/get_sms_content";
    this.getApiData(getApiContUrl, data, "contents");
    var caseData = {
      city: this.data.city,
      cid: screen.id,
      num: '3',
    };
    var getApinavUrl = app.globalData.smsbaoApi + "/batch/sapi/get_case_content";
    this.getApiData(getApinavUrl, caseData, "caseData");
  },

  onShareAppMessage: function() {
    return {
      title: '短信群发库 - 奇思妙想的短信内容，创意十足的短信模板',
      path: "/pages/index/index",
      success: function(res) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function(res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })

      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  // //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置，天气情况等信息
  loadCity: function(latitude, longitude) {
    var that = this;
    wx.request({
      url: app.globalData.mapApi + '/geocoder/v2/?ak=R4C1TODNU6HmoLhVHrG4vWPuqvvLvjE0&location=' + latitude + ',' + longitude + '&output=json&coordtype=wgs84ll',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        that.setData({
          city: res.data.result.addressComponent.city,
          positionShow: false,
        })
        that.getScreenData(res.data.result.addressComponent.city);
      },
    })

  },

  //数据加载
  onLoad: function(event) {
    let that = this;
    // 获取坐标
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        var latitude = res.latitude //维度
        var longitude = res.longitude //经度
        that.loadCity(latitude, longitude);
      },
      fail: function(err) {
        wx.openSetting({
          success: function(res) {
            if (res.authSetting != '') {
              wx.getLocation({
                success: function(res) {
                  var latitude = res.latitude //维度
                  var longitude = res.longitude //经度        
                  that.loadCity(latitude, longitude);
                },
              })
            }
          }
        })
      }
    });
    wx.showShareMenu({
      withShareTicket: true
    });
    //获取数据
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    var selectData = {
      cid: '',
      num: "6",
      page: "0",
      isChoice: 2
    };
    var getApiselectCont = app.globalData.smsbaoApi + "/batch/sapi/get_sms_content";
    that.getApiData(getApiselectCont, selectData, "select")
    var getApinavUrl = app.globalData.smsbaoApi + "/batch/sapi/get_sms_cate";
    that.getApiData(getApinavUrl, '', "nav");
  },
  //获取经典案例数据
  getScreenData: function(data) {
    let that = this;
    var screenData = {
      city: data,
      cid: '',
    };
    var getApinavUrl = app.globalData.smsbaoApi + "/batch/sapi/get_case_content";
    that.getApiData(getApinavUrl, screenData, "case_content");
  },

  //封装请求地址函数
  getApiData: function(url, data, settedKey, moreData = '') {
    let that = this
    wx.request({
      url: url,
      data: data,
      method: "post",
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.code == '200') {
          if (moreData == '') {
            var arrData = {};
            arrData[settedKey] = res.data.data;
            if (arrData[settedKey] == arrData['nav']) {
              for (var i in arrData['nav']) {
                arrData['nav'][i]['tool_image'] = app.globalData.smsbaoApi + "/batch/batch/" + arrData['nav'][i].tool_image;
              }
              arrData['nav'].reverse();
            }
            if (arrData[settedKey] == arrData['case_content']) {
              for (var i in arrData['case_content']) {
                arrData['case_content'][i]['case_image'] = app.globalData.smsbaoApi + "/batch/batch/" + arrData['case_content'][i].case_image;
              }
              arrData['case_content'].reverse();
            }
            wx.stopPullDownRefresh();
            that.setData(arrData);
          } else {
            if (res.data.data == undefined || res.data.data == '') {

              that.setData({
                requestLoadingComplete: false,
                requestLoading: true
              })
              wx.hideNavigationBarLoading();
              wx.stopPullDownRefresh();
              return false;
            } else {
              var updata = res.data.data;
              var data = that.data.contents.concat(updata);
              that.setData({
                contents: data,
                requestLoadingComplete: true,
                requestLoading: false
              })
            }
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
          }

        }
        setTimeout(function() {
          wx.hideLoading()
        }, 1000)
      }
    })
  },

  //跳转发送页面
  onBatchTo: function(event) {
    console.log(event)
    var data = event.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/batch/batch?data=' + JSON.stringify(data) + "&class=" + 0,
    })
  },
  //分享
  onContentShare: function(e) {
    // wx.previewImage({
    //   current: '/images/tmp/', // 当前显示图片的http链接
    //   urls: ['http://www.smsbao.com/style/images/banner1.jpg'] // 需要预览的图片http链接列表
    // })
    let that = this;
    var cid = e.currentTarget.dataset.cid;
    var tid = JSON.stringify(e.currentTarget.dataset.tid);
    const wxCanvasToTempFilePath = navdata.wxPromisify(wx.canvasToTempFilePath);
    const wxSaveImageToPhotosAlbum = navdata.wxPromisify(wx.saveImageToPhotosAlbum);
    var res = wx.getSystemInfoSync()
    //bgk图
    var dWidth = Math.ceil(res.windowWidth * 0.8);
    var dHeight = Math.ceil(res.windowHeight * 0.8);
    //canvas的X,Y
    var sWidth = Math.ceil(res.windowWidth - dWidth) / 2;
    var sHeight = 30;
    //二维码的X , Y
    var canvasWidth = dWidth - 60 + sWidth;
    var canvasHeight = dHeight - 60;
    //内容的X,Y
    var fillX = Math.ceil(dWidth / 2);
    var fillY = Math.ceil(dHeight / 4) + sHeight;
    this.setData({
      cid: cid,
      tid: tid,
      share_isShow: true,
      canvasClose: true,

      dWidth: res.windowWidth + "px",
      dHeight: dHeight + "px"
    });
    //   // 使用 wx.createContext 获取绘图上下文 context    
    var ctx = wx.createCanvasContext('shareCanvas');
    var text = "奇思妙想的短信内容,创意十足的短信模板";
    ctx.drawImage("/images/banner/share_img.png", sWidth, sHeight, dWidth, dHeight);
    ctx.drawImage("/images/banner/1530762585.png", canvasWidth, canvasHeight, 60, 60);
    ctx.drawImage("/images/banner/logo.png", sWidth, sHeight, 120, 60);
    ctx.setTextAlign('center');
    ctx.setFontSize(15);
    ctx.setFillStyle("#ffffff");
    ctx.fillText("奇思妙想的短信内容", fillX, fillY);
    ctx.setTextAlign('left');
    ctx.fillText("创意十足的短信模板", fillX, fillY + 20);
    ctx.setTextAlign('center');
    ctx.setFontSize(10);
    ctx.fillText("扫码查看更多行业经典短信内容", fillX, dHeight - 5);

    ctx.stroke()
    ctx.draw()
    setTimeout(function() {
      wxCanvasToTempFilePath({
        x: sWidth,
        y: sHeight,
        width: dWidth,
        height: dHeight,
        canvasId: 'shareCanvas'
      }, this).then(res => {
        return wxSaveImageToPhotosAlbum({
          filePath: res.tempFilePath
        })
      }).then(res => {
        wx.showToast({
          title: '已保存到相册'
        })
        that.setData({
          canvasClose: !that.data.canvasClose,
        })
      }).catch()
    }, 1000);

  },
  onClose: function(e) {
    this.setData({
      share_isShow: false,
    })

  },
})